package org.benjamin.lending.trusteeship.sumapay;

import java.sql.Timestamp;
import java.util.Map;

import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.BorrowInfo;
import org.benjamin.lending.domain.entity.TrusteeshipRequest;
import org.benjamin.lending.trusteeship.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.ObjectMapper;


public abstract class SumapayAbstractOperation extends AbstractService {
	
	private final Logger logger = LogManager.getLogger();

	//##将容易写错的参数名称用常量
	protected final String SIGNATURE = "signature";

	protected final String SUBLEDGER_LIST = "subledgerList";

	protected final String[] basicRequest = {"requestId","merchantCode"};

	final String[] BASIC_RESPONSE = {"requestId","result"};

	protected ObjectMapper objectMapper = new ObjectMapper();

	@Autowired
	public SumapayConfig sumaplayConfig;

	@Override
	public void beforeRequest(Map<String, Object> requestMap,String requestId,BorrowInfo borrowInfo) {
		requestMap.put("requestId", requestId);
		requestMap.put("merchantCode", sumaplayConfig.getMerchantCode());
		super.beforeRequest(requestMap,requestId,borrowInfo);
	}
	
	
	
	@Override
	protected void buildAbutmentUrl(Map<String, Object> requestMap) {
		requestMap.put("successReturnUrl", sumaplayConfig.getHostName()+"/trusteeship/success");
		requestMap.put("failReturnUrl", sumaplayConfig.getHostName()+"/trusteeship/fail");
		requestMap.put("noticeUrl", sumaplayConfig.getHostName()+"/trusteeship/notice");
		super.buildAbutmentUrl(requestMap);
	}

	@Override
	protected void buildUserIdIdentity(Map<String,Object> requestMap,String username){
		requestMap.put("userIdIdentity", this.getUserIdIdentity(username));
	}

	protected String getUserIdIdentity(String username){
		return "fnp2p_"+username;
	}


	@Override
	protected boolean signatureResponseValidity(TrusteeshipRequest trusteeshipRequest,Map<String, Object> responseMap) {
		String[] signatures = this.signatureResponse(responseMap);
		trusteeshipRequest.setRulesResponse(signatures[0]);
		String responseSignature = responseMap.get("signature").toString();
		return StringUtils.equals(responseSignature,signatures[1]);
	}



	@Override
	protected void processResponse(TrusteeshipRequest trusteeshipRequest, Map<String, Object> responseMap) throws RuntimeException {
		try{
			trusteeshipRequest.setProceesResult(new ObjectMapper().writeValueAsString(responseMap));	
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		trusteeshipRequest.setProcessTime(new Timestamp(System.currentTimeMillis()));
	}


	/**
	 * 加密，返回数组，0是未加密的明文，1是加密后的密文
	 * @param requestMap 参数
	 * @param keys 加密规则
	 * @return 0是未加密的明文，1是加密后的密文
	 */
	protected String[] buildSignature(Map<String,Object> requestMap, String... keys){
		StringBuilder rulesToValueBuffer = new StringBuilder();
		for(String key : keys){
			Object value = requestMap.get(key);
			if(value!= null){
				rulesToValueBuffer.append(value);
			}else{
				logger.warn("警告：加密规则字段{}未能在参数中查询到。",key);
			}
		}

		String valueToDigest = rulesToValueBuffer.toString();
		String signature = HmacUtils.hmacMd5Hex(sumaplayConfig.getSecuryKey(), valueToDigest);
		logger.info("签名明文：{} 加密后的密文是:{}",valueToDigest,signature);
		return new String[]{valueToDigest,signature};
	}
	
	
}
